<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发布管理 - 上传文档系统</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <!-- Quill 富文本编辑器 -->
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>
    <!-- 平台选择弹窗组件 -->
    <script src="js/platformSelectModal.js"></script>
    <!-- 配置 Tailwind CSS 自定义颜色和字体 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#6B7280',
                        success: '#10B981',
                        warning: '#F59E0B',
                        danger: '#EF4444',
                        info: '#3B82F6',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .sidebar-item {
                @apply flex items-center py-3 px-4 rounded-lg text-gray-600 hover:bg-primary/10 hover:text-primary transition-all duration-200 mb-2;
            }
            .sidebar-item.active {
                @apply bg-primary text-white font-medium;
            }
            .btn-primary {
                @apply bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-all duration-200;
            }
            .btn-secondary {
                @apply bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300 transition-all duration-200;
            }
            .card {
                @apply bg-white rounded-xl shadow-md p-6;
            }
            .input-field {
                @apply w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans min-h-screen flex flex-col">
    <div class="flex flex-1 overflow-hidden">
        <!-- 侧边栏 -->
        <aside class="w-64 bg-white shadow-lg flex-shrink-0">
            <div class="p-6">
                <h1 class="text-2xl font-bold text-gray-800 text-center">会员中心</h1>
                <div class="flex items-center justify-center mt-2">
                    <i class="fa fa-user-circle-o text-primary mr-2"></i>
                    <p class="text-gray-800 font-medium" id="sidebarUsername">13378091517</p>
                </div>
                <nav class="mt-8">
                    <ul>
                        <li>
                            <a href="index.html" class="sidebar-item">
                                <i class="fa fa-cloud-upload mr-3"></i>
                                上传文档
                            </a>
                        </li>
                        <li>
                            <a href="documents.html" class="sidebar-item" id="documentsLink">
                                <i class="fa fa-folder-open mr-3"></i>
                                文档管理
                            </a>
                        </li>
                        <li>
                            <a href="wechat-accounts.html" class="sidebar-item">
                                <i class="fa fa-weixin mr-3"></i>
                                公众号管理
                            </a>
                        </li>
                        <li>
                            <a href="wechat-account-management.html" class="sidebar-item">
                                <i class="fa fa-user-circle-o mr-3"></i>
                                账号管理
                            </a>
                        </li>
                        <li>
                            <a href="scraping.html" class="sidebar-item">
                                <i class="fa fa-scissors mr-3"></i>
                                抓取管理
                            </a>
                        </li>
                        <li>
                            <a href="database-config.html" class="sidebar-item">
                                <i class="fa fa-database mr-3"></i>
                                数据库配置
                            </a>
                        </li>
                        <li>
                            <a href="publish-management.html" class="sidebar-item active">
                                <i class="fa fa-paper-plane mr-3"></i>
                                发布管理
                            </a>
                        </li>
                        <li>
                            <a href="#" class="sidebar-item" id="logoutLink">
                                <i class="fa fa-sign-out mr-3"></i>
                                退出登录
                            </a>
                        </li>
                    </ul>
                </nav>
            </div>
        </aside>

        <!-- 主内容区 -->
        <main class="flex-1 p-8 overflow-y-auto min-h-0">
            <div class="container mx-auto">
                <div class="mb-8">
                    <h2 class="text-2xl font-bold text-gray-800">发布管理</h2>
                    <p class="text-gray-600 mt-2">创建并发布文章或图片到各平台</p>
                </div>

                <!-- 内容编辑区 -->
                <div class="card mb-6">
                    <h3 class="text-lg font-semibold text-gray-800 mb-4">发布内容</h3>
                    
                    <!-- 标题输入 -->
                    <div class="mb-4">
                        <label for="contentTitle" class="block text-sm font-medium text-gray-700 mb-1">标题</label>
                        <input type="text" id="contentTitle" class="input-field" placeholder="请输入标题">
                    </div>
                    
                    <!-- 内容输入 - 富文本编辑器 -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-1">内容</label>
                        <div id="editor" class="border border-gray-300 rounded-lg"></div>
                        <input type="hidden" id="contentText">
                    </div>
                    
                    <!-- 图片上传 -->
                    <div class="mb-4">
                        <label for="imageUpload" class="block text-sm font-medium text-gray-700 mb-1">图片</label>
                        <div class="relative">
                            <input type="file" id="imageUpload" accept="image/*" class="hidden">
                            <button type="button" id="selectImageBtn" class="btn-secondary">
                                <i class="fa fa-image mr-2"></i>选择图片
                            </button>
                            <div id="imagePreview" class="mt-3 hidden">
                                <img id="previewImg" src="" alt="预览图" class="max-w-full max-h-64 rounded-lg border border-gray-200">
                                <button type="button" id="removeImageBtn" class="mt-2 text-danger text-sm">
                                    <i class="fa fa-times mr-1"></i>移除图片
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 发布类型显示 -->
                    <div class="mt-4">
                        <span class="text-sm font-medium text-gray-700">发布类型：</span>
                        <span id="publishTypeDisplay" class="text-primary font-medium">文章</span>
                    </div>
                </div>
                
                <!-- 平台选择弹窗将由组件动态创建 -->

                <!-- 操作按钮 -->
                <div class="flex justify-end space-x-4">
                    <button id="saveDraftBtn" class="btn-secondary">
                        <i class="fa fa-save mr-2"></i>保存草稿
                    </button>
                    <button id="publishToLibraryBtn" class="btn-secondary bg-info hover:bg-info/90 text-white">
                        <i class="fa fa-book mr-2"></i>发布到文库
                    </button>
                    <button id="publishBtn" class="btn-primary">
                        <i class="fa fa-paper-plane mr-2"></i>立即发布
                    </button>
                </div>
            </div>
        </main>
    </div>

    <!-- JavaScript -->
    <script>
        // 初始化富文本编辑器
        const quill = new Quill('#editor', {
            theme: 'snow',
            placeholder: '请输入内容...',
            modules: {
                toolbar: [
                    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                    ['bold', 'italic', 'underline', 'strike'],
                    [{ 'color': [] }, { 'background': [] }],
                    [{ 'align': [] }],
                    ['blockquote', 'code-block'],
                    [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                    [{ 'script': 'sub'}, { 'script': 'super' }],
                    [{ 'indent': '-1'}, { 'indent': '+1' }],
                    ['link', 'image'],
                    ['clean']
                ]
            }
        });
        
        // DOM元素引用
        const imageUpload = document.getElementById('imageUpload');
        const selectImageBtn = document.getElementById('selectImageBtn');
        const imagePreview = document.getElementById('imagePreview');
        const previewImg = document.getElementById('previewImg');
        const removeImageBtn = document.getElementById('removeImageBtn');
        const contentTitle = document.getElementById('contentTitle');
        const contentText = document.getElementById('contentText');
        const publishTypeDisplay = document.getElementById('publishTypeDisplay');
        const publishBtn = document.getElementById('publishBtn');
        const saveDraftBtn = document.getElementById('saveDraftBtn');
        
        // 初始化平台选择弹窗组件
        if (!window.platformSelectModal) {
            window.platformSelectModal = initPlatformSelectModal();
        }
        
        // 图片选择功能
        selectImageBtn.addEventListener('click', function() {
            imageUpload.click();
        });
        
        // 图片预览
        imageUpload.addEventListener('change', function(e) {
            if (e.target.files && e.target.files[0]) {
                const reader = new FileReader();
                reader.onload = function(event) {
                previewImg.src = event.target.result;
                imagePreview.classList.remove('hidden');
                updatePublishType();
            };
                reader.readAsDataURL(e.target.files[0]);
            }
        });
        
        // 移除图片
        removeImageBtn.addEventListener('click', function() {
            imageUpload.value = '';
            imagePreview.classList.add('hidden');
            previewImg.src = '';
            updatePublishType();
        });
        
        // 从富文本编辑器获取纯文本内容
        function getEditorTextContent() {
            const delta = quill.getContents();
            let text = '';
            delta.ops.forEach(op => {
                if (op.insert && typeof op.insert === 'string') {
                    text += op.insert;
                }
            });
            return text.trim();
        }
        
        // 更新发布类型显示
        function updatePublishType() {
            const hasText = getEditorTextContent().length > 0;
            const hasImage = imagePreview.classList.contains('hidden') === false;
            
            if (hasText && !hasImage) {
                publishTypeDisplay.textContent = '文章';
            } else if (!hasText && hasImage) {
                publishTypeDisplay.textContent = '图片';
            } else if (hasText && hasImage) {
                publishTypeDisplay.textContent = '图文';
            } else {
                publishTypeDisplay.textContent = '文章';
            }
        }
        
        // 监听内容变化，自动更新发布类型
        quill.on('text-change', updatePublishType);
        
        // 保存草稿
        saveDraftBtn.addEventListener('click', function() {
            const title = contentTitle.value.trim();
            const content = quill.root.innerHTML; // 获取HTML内容
            const hasImage = imagePreview.classList.contains('hidden') === false;
            
            if (!title) {
                alert('请输入标题');
                return;
            }
            
            if (!getEditorTextContent() && !hasImage) {
                alert('请输入内容或选择图片');
                return;
            }
            
            // 更新隐藏字段的值
            contentText.value = content;
            
            // 这里可以添加保存草稿的逻辑
            alert('草稿已保存');
        });
        
        // 打开发布平台选择弹窗
        publishBtn.addEventListener('click', function() {
            const title = contentTitle.value.trim();
            const content = quill.root.innerHTML; // 获取HTML内容
            const hasImage = imagePreview.classList.contains('hidden') === false;
            
            if (!title) {
                alert('请输入标题');
                return;
            }
            
            if (!getEditorTextContent() && !hasImage) {
                alert('请输入内容或选择图片');
                return;
            }
            
            // 更新隐藏字段的值
            contentText.value = content;
            
            // 准备文档数据（与文档管理页面结构保持一致）
            const documentData = [{
                title: title,
                id: null, // 新发布的内容没有ID
                content: content,
                plainText: getEditorTextContent(),
                hasImage: hasImage,
                publishType: publishTypeDisplay.textContent
            }];
            
            // 确保platformSelectModal存在
            if (!window.platformSelectModal) {
                initPlatformSelectModal();
            }
            
            // 重写平台选择弹窗的handleConfirm方法
            const originalHandleConfirm = window.platformSelectModal.handleConfirm;
            window.platformSelectModal.handleConfirm = async function() {
                if (this.currentPublishData.selectedPlatforms.length === 0) {
                    alert('请至少选择一个发布平台');
                    return;
                }
                
                // 获取发布内容
                const title = contentTitle.value.trim();
                const content = quill.root.innerHTML;
                const plainText = getEditorTextContent();
                const hasImage = imagePreview.classList.contains('hidden') === false;
                
                // 更新隐藏字段的值
                contentText.value = content;
                
                // 构建发布数据
                const publishData = {
                    documents: [{
                        title: title,
                        content: content,
                        plainText: plainText,
                        hasImage: hasImage,
                        publishType: publishTypeDisplay.textContent
                    }],
                    platforms: this.currentPublishData.selectedPlatforms,
                    isBatch: false
                };
                
                console.log('发布数据:', publishData);
                
                try {
                    // 调用后端发布接口
                    const response = await fetch('/api/publish', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        credentials: 'same-origin',
                        body: JSON.stringify(publishData)
                    });
                    
                    if (!response.ok) {
                        throw new Error(`HTTP错误! 状态码: ${response.status}`);
                    }
                    
                    let data;
                    try {
                        data = await response.json();
                    } catch (jsonError) {
                        console.error('解析响应JSON失败:', jsonError);
                        throw new Error('响应格式错误');
                    }
                    
                    if (data.success) {
                        alert('发布成功! ' + (data.platformResponse || ''));
                    } else {
                        alert('发布失败: ' + (data.message || '未知错误'));
                    }
                } catch (error) {
                    console.error('发布请求失败:', error);
                    alert('发布请求失败: ' + error.message);
                } finally {
                    // 隐藏弹窗
                    this.hideModal();
                    
                    // 恢复原始handleConfirm方法
                    window.platformSelectModal.handleConfirm = originalHandleConfirm;
                }
            };
            
            // 打开平台选择弹窗
            window.platformSelectModal.showModal(documentData, false);
        });
        
        // 发布到文库功能
        document.getElementById('publishToLibraryBtn').addEventListener('click', function() {
            const title = contentTitle.value.trim();
            const content = quill.root.innerHTML;
            const plainText = getEditorTextContent();
            const hasImage = imagePreview.classList.contains('hidden') === false;
            
            if (!title) {
                alert('请输入标题');
                return;
            }
            
            if (!plainText && !hasImage) {
                alert('请输入内容或选择图片');
                return;
            }
            
            // 创建分类选择弹窗
            createCategorySelectModal();
        });
        
        // 创建分类选择弹窗
        function createCategorySelectModal() {
            // 检查弹窗是否已存在
            if (document.getElementById('categoryModal')) {
                document.getElementById('categoryModal').classList.remove('hidden');
                return;
            }
            
            // 创建弹窗HTML
            const modalHTML = `
                <div id="categoryModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div class="bg-white rounded-lg shadow-xl w-full max-w-md max-h-[80vh] overflow-hidden">
                        <div class="p-6">
                            <div class="flex justify-between items-center mb-4">
                                <h2 class="text-xl font-bold text-gray-800">选择文档分类</h2>
                                <button id="closeCategoryModal" class="text-gray-500 hover:text-gray-700 focus:outline-none">
                                    <i class="fa fa-times text-xl"></i>
                                </button>
                            </div>
                            
                            <!-- 分类选择 -->
                            <div class="mb-4">
                                <div class="relative">
                                    <input type="text" id="categoryDisplay" 
                                        class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" 
                                        placeholder="选择分类" readonly>
                                    <div id="categoryDropdown" class="absolute left-0 right-0 top-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg z-10 max-h-60 overflow-y-auto hidden">
                                        <ul id="categoryList" class="py-1"></ul>
                                    </div>
                                </div>
                                <input type="hidden" id="selectedCategoryId" value="">
                            </div>
                            
                            <div class="flex justify-end">
                                <button id="cancelCategorySelect" class="btn-secondary mr-2">取消</button>
                                <button id="confirmCategorySelect" class="btn-primary">确认</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', modalHTML);
            
            // 初始化分类数据
            initCategorySelection();
            
            // 绑定事件
            document.getElementById('closeCategoryModal').addEventListener('click', function() {
                document.getElementById('categoryModal').classList.add('hidden');
            });
            
            document.getElementById('cancelCategorySelect').addEventListener('click', function() {
                document.getElementById('categoryModal').classList.add('hidden');
            });
            
            document.getElementById('confirmCategorySelect').addEventListener('click', async function() {
                const categoryId = document.getElementById('selectedCategoryId').value;
                const categoryName = document.getElementById('categoryDisplay').value;
                
                if (!categoryId || !categoryName) {
                    alert('请选择文档分类');
                    return;
                }
                
                // 显示加载状态
                const confirmButton = this;
                const originalText = confirmButton.textContent;
                confirmButton.disabled = true;
                confirmButton.textContent = '提交中...';
                
                try {
                    // 转换内容并上传，使用Promise处理异步操作
                    await convertAndUploadToLibrary(categoryId, categoryName);
                    document.getElementById('categoryModal').classList.add('hidden');
                } catch (error) {
                    console.error('上传失败:', error);
                    alert('上传失败，请重试: ' + error.message);
                } finally {
                    // 恢复按钮状态
                    confirmButton.disabled = false;
                    confirmButton.textContent = originalText;
                }
            });
        }
        
        // 初始化分类选择
        function initCategorySelection() {
            const categoryDisplay = document.getElementById('categoryDisplay');
            const categoryDropdown = document.getElementById('categoryDropdown');
            const categoryList = document.getElementById('categoryList');
            
            // 加载分类
            loadCategoriesForModal();
            
            // 点击显示/隐藏下拉菜单
            categoryDisplay.addEventListener('click', function(e) {
                e.stopPropagation();
                categoryDropdown.classList.toggle('hidden');
            });
            
            // 点击外部关闭下拉菜单
            document.addEventListener('click', function(event) {
                if (!categoryDisplay.contains(event.target) && !categoryDropdown.contains(event.target)) {
                    categoryDropdown.classList.add('hidden');
                }
            });
            
            // 阻止下拉菜单内部点击冒泡
            categoryDropdown.addEventListener('click', function(e) {
                e.stopPropagation();
            });
        }
        
        // 加载分类数据
        function loadCategoriesForModal() {
            const categoryList = document.getElementById('categoryList');
            categoryList.innerHTML = '<li class="text-gray-500 py-2 px-3">正在加载分类...</li>';
            
            const xhr = new XMLHttpRequest();
            xhr.open('GET', '/api/categories', true);
            
            xhr.onload = function() {
                if (xhr.status === 200) {
                    try {
                        const categories = JSON.parse(xhr.responseText);
                        renderCategoriesForModal(categories);
                    } catch (e) {
                        categoryList.innerHTML = '<li class="text-red-500 py-2 px-3">分类加载失败</li>';
                    }
                } else {
                    categoryList.innerHTML = '<li class="text-red-500 py-2 px-3">分类加载失败</li>';
                }
            };
            
            xhr.onerror = function() {
                categoryList.innerHTML = '<li class="text-red-500 py-2 px-3">网络错误</li>';
            };
            
            xhr.send();
        }
        
        // 渲染分类列表
        function renderCategoriesForModal(categories) {
            const categoryList = document.getElementById('categoryList');
            categoryList.innerHTML = '';
            
            // 构建分类树
            const categoryMap = {};
            const rootCategories = [];
            
            // 首先创建所有分类的映射
            categories.forEach(category => {
                categoryMap[category.id] = {
                    id: category.id,
                    name: category.name,
                    pid: category.pid,
                    children: []
                };
            });
            
            // 构建树形结构
            categories.forEach(category => {
                if (category.pid === 0) {
                    rootCategories.push(categoryMap[category.id]);
                } else if (categoryMap[category.pid]) {
                    categoryMap[category.pid].children.push(categoryMap[category.id]);
                }
            });
            
            // 递归渲染分类
            function renderCategory(category, level = 0) {
                const indent = level * 24; // 每个级别缩进24px
                const categoryItem = document.createElement('li');
                categoryItem.className = `py-2 pl-3 pr-3 cursor-pointer hover:bg-gray-100 transition-all`;
                
                // 设置缩进样式
                categoryItem.style.paddingLeft = `${indent + 12}px`;
                
                // 根据级别设置不同的样式
                if (level === 0) {
                    categoryItem.classList.add('font-medium', 'text-gray-800', 'border-l-4', 'border-primary');
                } else if (level === 1) {
                    categoryItem.classList.add('text-gray-700', 'border-l-2', 'border-primary/50');
                } else {
                    categoryItem.classList.add('text-gray-600', 'border-l-2', 'border-gray-200');
                }
                
                categoryItem.textContent = category.name;
                categoryItem.onclick = () => selectCategoryForModal(category.id, category.name);
                categoryList.appendChild(categoryItem);
                
                // 递归渲染子分类
                if (category.children && category.children.length > 0) {
                    category.children.forEach(child => {
                        renderCategory(child, level + 1);
                    });
                }
            }
            
            // 渲染所有根分类及其子分类
            rootCategories.forEach(root => {
                renderCategory(root);
            });
        }
        
        // 选择分类
        function selectCategoryForModal(categoryId, categoryName) {
            document.getElementById('categoryDisplay').value = categoryName;
            document.getElementById('selectedCategoryId').value = categoryId;
            document.getElementById('categoryDropdown').classList.add('hidden');
        }
        
        // 转换内容并上传到文库
function convertAndUploadToLibrary(categoryId, categoryName) {
    return new Promise((resolve, reject) => {
        // 验证参数
        if (!categoryId) {
            alert('请先选择分类');
            reject(new Error('未选择分类'));
            return;
        }
        
        const title = contentTitle.value.trim();
        if (!title) {
            alert('请输入文档标题');
            reject(new Error('未输入文档标题'));
            return;
        }
        
        const content = quill.root.innerHTML;
        const plainText = getEditorTextContent();
        const hasImage = imagePreview.classList.contains('hidden') === false;
        
        // 创建一个临时的上传进度对话框
        const progressDialog = createProgressDialog();
        
        // 1. 先向服务器发送HTML内容，请求转换为Word
        // 使用fetch API发送内容到服务器进行转换
        fetch('/api/save-document', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: 'content=' + encodeURIComponent(content) + '&fileName=' + encodeURIComponent(title + '.doc')
        })
        .then(response => response.json())
        .then(data => {
            if (data.success && data.filePath) {
                // 转换成功，获取到文件路径后再上传
                updateProgressDialog(progressDialog, 50, '文件保存成功，正在上传...');
                
                // 2. 由于服务器已经保存了文件，我们直接上传这个文件
                // 创建Blob对象作为文件内容
                const fileName = title + '.doc';
                // 为了演示，我们创建一个包含文件路径信息的文本文件
                const fileContent = new Blob([data.filePath], { type: 'text/plain' });
                const file = new File([fileContent], fileName, { 
                    type: 'application/msword' 
                });
                
                // 3. 创建表单数据并上传
                const formData = new FormData();
                formData.append('file', file);
                formData.append('title', title);
                formData.append('categoryId', categoryId);
                formData.append('type', 'free'); // 可以根据需要设置文档类型
                formData.append('source', 'publish-management'); // 标记来源
                
                // 发送上传请求
                const xhr = new XMLHttpRequest();
                
                // 监听上传进度
                xhr.upload.addEventListener('progress', (e) => {
                    if (e.lengthComputable) {
                        // 转换50% + 上传50%
                        const percent = 50 + Math.round((e.loaded / e.total) * 50);
                        updateProgressDialog(progressDialog, percent, '正在上传到文库...');
                    }
                });
                
                // 监听请求完成
                xhr.addEventListener('load', () => {
                    closeProgressDialog(progressDialog);
                    
                    // 处理响应
                    if (xhr.status === 200) {
                        try {
                            const result = JSON.parse(xhr.responseText);
                            if (result.code === 0) {
                                alert('发布到文库成功！已分类到：' + (categoryName || '未分类'));
                                resolve();
                            } else {
                                const errorMsg = '上传失败：' + (result.message || '未知错误');
                                alert(errorMsg);
                                reject(new Error(errorMsg));
                            }
                        } catch (error) {
                            console.error('解析响应失败:', error);
                            alert('上传成功，但处理响应时出错');
                            reject(error);
                        }
                    } else {
                        const errorMsg = '上传失败，服务器返回错误：' + xhr.status;
                        alert(errorMsg);
                        reject(new Error(errorMsg));
                    }
                });
                
                // 监听请求错误
                xhr.addEventListener('error', (error) => {
                    closeProgressDialog(progressDialog);
                    alert('网络错误，请稍后重试');
                    reject(error);
                });
                
                // 发送POST请求到上传接口
                xhr.open('POST', '/upload', true);
                xhr.send(formData);
            } else {
                closeProgressDialog(progressDialog);
                const errorMsg = '文件保存失败：' + (data.message || '未知错误');
                alert(errorMsg);
                reject(new Error(errorMsg));
            }
        })
        .catch(error => {
            closeProgressDialog(progressDialog);
            console.error('转换请求失败:', error);
            alert('文件转换请求失败，请检查网络连接后重试');
            reject(error);
        });
    });
}

// 创建进度对话框
function createProgressDialog() {
    // 创建一个简单的进度对话框
    const dialog = document.createElement('div');
    dialog.className = 'fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50';
    dialog.innerHTML = `
        <div class="bg-white p-6 rounded-lg shadow-lg w-1/3">
            <h3 class="text-lg font-medium mb-4">上传进度</h3>
            <div class="w-full bg-gray-200 rounded-full h-2.5 mb-2">
                <div id="progressBar" class="bg-blue-600 h-2.5 rounded-full" style="width: 0%"></div>
            </div>
            <p id="progressText" class="text-sm text-gray-600">正在准备上传...</p>
        </div>
    `;
    document.body.appendChild(dialog);
    return dialog;
}

// 更新进度对话框
function updateProgressDialog(dialog, percent, message) {
    const progressBar = dialog.querySelector('#progressBar');
    const progressText = dialog.querySelector('#progressText');
    if (progressBar && progressText) {
        progressBar.style.width = percent + '%';
        progressText.textContent = message;
    }
}

// 关闭进度对话框
function closeProgressDialog(dialog) {
    if (dialog && dialog.parentNode) {
        dialog.parentNode.removeChild(dialog);
    }
}
    </script>
</body>
</html>